package com.moyq5.permit.center.core.dao.impl;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;

import com.moyq5.mvc.framework.dao.BasicDao;
import com.moyq5.mvc.framework.dao.ExampleQuery;
import com.moyq5.mvc.framework.general.Paging;
import com.moyq5.permit.center.bean.entity.Charge;
import com.moyq5.permit.center.bean.entity.Charge_;
import com.moyq5.permit.center.bean.search.Charge4Search;
import com.moyq5.permit.center.core.dao.ChargeDao;


/**
 * @author Moyq5's MvcMaker Tools
 */
@Repository
public class ChargeDaoImpl extends BasicDao<Charge, Charge4Search> implements ChargeDao {

	public ChargeDaoImpl() {
		super(Charge.class);
	}

	@Override
	protected CriteriaQuery<Charge> createSearchCriteria(ExampleQuery<Charge> eq, Charge4Search t4s) {
		CriteriaQuery<Charge> cq = eq.getCriteriaQuery();
		
		@SuppressWarnings("unchecked")
		Root<Charge> cr = (Root<Charge>) cq.getRoots().iterator().next();
		List<Predicate> ps = new ArrayList<Predicate>();
		ps.add(cq.getRestriction());
		
		CriteriaBuilder cb = em().getCriteriaBuilder();
		
		if (null != t4s.getOrderTimeGt()) {
			ps.add(cb.greaterThanOrEqualTo(cr.get(Charge_.orderTime), t4s.getOrderTimeGt()));
		}
		if (null != t4s.getOrderTimeLt()) {
			ps.add(cb.lessThanOrEqualTo(cr.get(Charge_.orderTime), t4s.getOrderTimeLt()));
		}
		// TODO 在这里实现其它属性（条件）的查询
		
		cq.where(ps.toArray(new Predicate[ps.size()]));
		
		return cq;
	}

	@Override
	public BigDecimal sumAmount(Charge4Search order4s, String searchWord) {
		Paging pi = new Paging();
		pi.setSearchWord(searchWord);
		CriteriaQuery<Charge> cq = createSearchCriteria(order4s, pi);
		
		CriteriaBuilder cb = em().getCriteriaBuilder();
		CriteriaQuery<BigDecimal> ccq = cb.createQuery(BigDecimal.class);
		Root<Charge> ccr = ccq.from(cq.getResultType());
		ccr.alias(cq.getRoots().iterator().next().getAlias());
		ccq.select(cb.sum(ccr.get(Charge_.amount)));
		ccq.where(cq.getRestriction());
		TypedQuery<BigDecimal> tq = em().createQuery(ccq);
		return tq.getSingleResult();
	}
	
}

